<?php

namespace app\index\model;

use app\index\controller\Tag;
use app\index\validate\Article as ValidateArticle;
use app\service\Score;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Session;
use think\Model;

class Article extends Model
{
    public function getArticleData($pid)
    {
        $data = $this->where('id', $pid)->with(['profile' => function ($query) {
            $query->field('id , username ,head_icon , signature,nickname');
        }])->find();
        if (!$data) return false;
        // $data['username'] = User::where('id', $data['user_id'])->value('username');
        $data['update_name'] = User::where('id', $data['update_uid'])->value('nickname');
        return $data;
    }
    public function profile()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
    // 付费文章阅读权限查看
    public function readDataHandel($art_id, $data)
    {
        $uid = Session::has('user') ? Session::get('user.user_id') : 0;
        // 是否收藏
        $data['isCollect'] = Collect::where(['article_id' => $art_id, 'user_id' => $uid])->findOrEmpty()->isEmpty() == true ? 0 : 1;

        $artData = $this->find($art_id);
        // 是否关注
        $data['isFollow'] = Db::name('follow')->where(['user_id' => $uid, 'follow_user_id' => $artData->user_id])->find() ? true : false;
        switch ($data['type']) {
            // 回复查看
            case 0:
                // 回复文章
                $isComment = Comment::where(['user_id' => $uid, 'article_id' => $art_id])->findOrEmpty()->isEmpty();
                $tip =   '<fieldset class="layui-elem-field">
            <legend>温馨提示</legend>
            <div class="layui-field-box">
                游客，如果您要查看本帖隐藏内容请回复 </div> </fieldset>';
                if (Session::get('user.user_id') == $artData->user_id) {
                    $data['content'] = $data['content'];
                } else {
                    $data['content'] = $isComment == true ?  $tip : $data['content'];
                }
                $data['isComment'] = $isComment == true ? 0 : 1;
                break;
            // 付费文章
            case 2:
                $isPay = PayedArt::where(['user_id' => $uid, 'article_id' => $art_id])->findOrEmpty()->isEmpty();
                $score = $data['score'];
                $tip =   '<fieldset class="layui-elem-field">
                            <legend>温馨提示</legend>
                            <div class="layui-field-box">
                                阅读该文章需支付积分 [ ' . $score . ' ]</div>
                                    <div class="pay layui-clear">
                                        <button class="layui-btn layui-btn-primary layui-border" onclick="payArt(' . $art_id . ')">立即支付</button>
                                    </div>
                                </fieldset>
                                ';
                if (Session::get('user.user_id') == $artData->user_id) {
                    $data['content'] = $data['content'];
                } else {
                    $data['content'] = $isPay == true ? $tip  : $data['content'];
                }
                $data['isPay'] = $isPay == true ? 0 : 1;
                break;
            // 悬赏文章
            case 3:
                // 判断是否采纳 (可采纳多个 ？ 还是只能采纳单个)
                // $isAdopt = ArtAdopt::where(['article_id' => $art_id])->findOrEmpty()->isEmpty();
                $data['isAdopt'] = $artData['status'] == 1 ? 1 : 0;
                if ($data['isAdopt']) {
                    $data['answer'] = Db::name('user')->where('id', $artData['user_id'])->field('id,head_icon,nickname')->find();
                    $data['answer_comment'] = Db::name('comment')->where('id', $artData['comment_id'])->value('comment');
                }
                break;
        }

        // tag标签处理
        $data['tagList'] = (new Tap())->get($data['id']);
        return $data;
    }

    public function list($data = [])
    {
        $tagId = @$data['tap'] ?? '';
        $title = @$data['title'];
        $category_id = @$data['category_id'];
        $user_id = @$data['user_id'];
        // 显示类型 -> 热门 | 最新
        $type = @$data['type'];
        // 显示类型
        // -------- 分页额外搜索参数 ---------
        $pageQuery = [];
        $pageQuery['query']['type'] = $type;
        $limit = isset($data['limit']) ? $data['limit'] : 5;
        $pageQuery['list_rows'] = $limit;
        // 分类下的文章
        if (array_key_exists('parentCid', $data) || array_key_exists('category_id', $data)) {
            $pageQuery['query']['cid'] = is_array($category_id) ? $data['parentCid'] : $category_id;
        }
        // 个人的文章（用户）
        if (array_key_exists('user_id', $data)) {
            $pageQuery['query']['uid'] = $data['user_id'];
        }
        // 标签文章
        if (@$tagId) {
            $pageQuery['query']['tag'] = $tagId;
        }

        // -------------------------------
        // 自定义搜索参数 ， 数据库无此字段 ， 删除处理
        unset($data['title'], $data['parentCid'], $data['type'], $data['limit'], $data['tap']);
        if (array_key_exists('tap', $data)) {
            if (is_numeric($data['tap'])) {
                $hasTag = Db::name('tap')->where(['is_show' => 1, 'id' => $data['tap']])->find();
                if ($hasTag) {
                    $tagId = $data['tap'];
                }
            }
        }
        if (array_key_exists('list', $data)) {
            $list = $data['list'];
        } else {

            // 查看多个父类下的文章 -- 分类下的列表 -->显示分类下一级分类下全部文章
            if (is_array(@$category_id)) {
                $cateIdArr = implode(',', $category_id);
                $list = $this->whereIn('category_id', $cateIdArr)->where($data)->order('is_top desc,is_hot desc,id desc,sort asc');
                if ($type == 'hot') {
                    $list->where('heat', '>', '100');
                } else if ($type == 'new') {
                    // 新发布 -> 三天内
                    $list->whereIn('category_id', $cateIdArr)->whereBetweenTime('create_time', date('Y-m-d', time()), date('Y-m-d', strtotime('+3 day')));
                }
            } else {
                // 首页 | 用户简介 展示的文章
                $query = ['status' => 1];
                if ($category_id) $query['category_id'] = $category_id;
                if ($user_id) $query['user_id'] = $user_id;
                $list = $this->where($query)->order('is_top desc,is_hot desc,id desc ,sort asc');
            }
            // 文章搜索
            if (!empty($title)) {
                $list->where('title', 'like', '%' . $title . '%');
            }
            // 标签文章
            if (!empty(@$tagId)) {
                $list->where('tap_id', 'like', '%' . $tagId . '%');
            }
            $list = $list->paginate($pageQuery);
        }
        $todayNum = 0;
        foreach ($list as $k => $item) {
            if (date('d', strtotime($item['create_time'])) == date('d', time())) $todayNum++;
            // 最父级分类
            // $list[$k]['category'] = (new Category())->getParentCate($item['category_id']);
            $list[$k]['category']  = Category::find($item['category_id'])->category;
            $list[$k]['commentCount'] = Comment::where('article_id', $item['id'])->count();
            $list[$k]['collectCount'] = Collect::where('article_id', $item['id'])->count();
            $list[$k]['nickname'] = User::where('id', $item['user_id'])->value('nickname');
            $list[$k]['headIcon'] = User::where('id', $item['user_id'])->value('head_icon');
            if ($list[$k]->tap_id != '') $list[$k]['tapList'] = (new Tap)->get($item['id']);
            else $list[$k]['tapList'] = [];
        }
        $data = [
            'list' => $list,
            'totalNum' => $list->total(),
            'todayNum' => $todayNum
        ];
        return $data;
    }
    // 文章添加 -> 参数验证
    static public function handleParam(array $param)
    {
        if (!empty($param['sign'])) {
            unset($param['sign']);
        }
        if (array_key_exists('type', $param) && $param['type'] != 3 && $param['type'] != 2) {
            unset($param['score']);
        }
        if ($param['type'] == 3 && empty(@$param['comType'])) {
            return '请选择文章评论的显示方式';
        }
        try {
            validate(ValidateArticle::class)->check($param);
            $uid = Session::get('user.user_id');
            if ($param['type'] == 3 && empty(@$param['comType'])) return '请选择文章评论回复类型';
            $param['user_id'] = Session::get('user.user_id');
            // @param type 2付费 3 悬赏
            $param['tap_id'] = !empty(@$param['tap_id']) ? Tap::handleSpliceToArr($param['tap_id']) : '';
            $content = remove_xss(str_replace("<p><br/></p>", '', $param['content']));
            $param['content'] = str_replace('<pre>', '<pre class="layui-code code">', $content);
            // 是否存在分类 且为三级分类
            // dump($param);die;
            $checkCate = (new Category)->isThree($param['category_id']);
            if ($checkCate != 1)   return $checkCate;
            // 更新文章判断
            if (isset($param['id'])) {
                $artData = self::find($param['id']);
                // 更换文章类型
                if ($param['type'] == 3 && $artData['type'] != 3) {
                    $score = $param['score'];
                    // 发送消息及扣除对应积分
                    $pay = Score::compare($uid, $score);
                    if ($pay != 1) {
                        return '当前积分不足,还差积分[' . abs($pay) . ']';
                    }
                    $msg = "更新文章模式为悬赏，扣除积分[ $score ]";
                    Msg::send(0, $uid, ['content' => $msg]);
                    ArtAdopt::create(['author_id' => Session::get('user.user_id'), 'type' => $param['comType'], 'article_id' => $param['id']]);
                } else {
                    // 如果之前为悬赏文章 ， 现在则不支持更改积分
                    unset($param['score']);
                }
                // 如果为悬赏文章，则不能更换文章类型 其他属性可以更换
                if ($artData['type'] == 3 && $param['type'] != 3)  return '当前文章类型不可更改哦！';
                if ($artData['title'] == $param['title'] && $artData['content'] == $param['content'] && $artData['img_path'] == $param['img_path']) {
                    // 防止提交status 为 1
                    $param['status'] = $artData->status;
                } else {
                    $param['status'] = 0;
                }
            } else if ($param['type']  == 3) {
                // 当添加悬赏文章需 扣减积分 有id则是更新文章
                $score = $param['score'];
                // 发送消息及扣除对应积分
                $pay = Score::compare($uid, $score);
                if ($pay != 1) {
                    return '当前积分不足,还差积分[' . abs($pay) . ']';
                }
                $msg = "发布悬赏文章，扣除积分[ $score ]";
                Msg::send(0, $uid, ['content' => $msg]);
            }
            return $param;
        } catch (ValidateException $e) {
            return $e->getError();
        }
    }
    public function del($art_id)
    {
        $isHas = $this->where(['user_id' => Session::get('user.user_id', 'id'), 'id' => $art_id])->findOrEmpty()->isEmpty();
        if ($isHas) return '该文章不存在';
        $artCtn = $this->find($art_id)->content;
        // 图片删除
        $imgNum = preg_match_all("/.*<img src=\"(.*)\".*/", $artCtn, $img);
        if ($imgNum > 0) {
            $imgArr = [];
            foreach ($img[1] as $k => $v) {
                array_push($imgArr, strstr($v, '" alt=', true));
            }
            foreach ($imgArr as $j) {
                $path = app()->getRootPath() . 'public' . $j;
                if (file_exists($path))
                    unlink($path);
            }
        }
        $article = Article::with('comments')->find($art_id);
        if ($article) {
            $res = $article->together(['comments'])->delete();
        }
        // 先不删除采纳表，用来历史查看 可删可不删
        // if($article['type'] == 3){
        //     ArtAdopt::where(['article_id' => $art_id])->delete();
        // }
        $res = Article::destroy($art_id);
        if ($res) return 1;
    }
}
